package com.lancoo.klgcourseware.ui.fragment.basicTrain;

import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewStub;

import androidx.fragment.app.FragmentTransaction;

import com.google.gson.Gson;
import com.lancoo.klgcourseware.R;
import com.lancoo.klgcourseware.entity.WordArticulation;
import com.lancoo.klgcourseware.entity.bean.KlgCommonBean;
import com.lancoo.klgcourseware.manager.KlgLocalMediaManager;
import com.lancoo.klgcourseware.manager.KlgMediaManager;
import com.lancoo.klgcourseware.ui.activity.KlgBasicTrainActivity;
import com.lancoo.klgcourseware.ui.fragment.pronounceTrain.PronounceBaseFragment;
import com.lancoo.klgcourseware.ui.fragment.pronounceTrain.PronounceFastRepeatTrainFragment;
import com.lancoo.klgcourseware.ui.fragment.pronounceTrain.PronounceReadingTrainFragment;
import com.lancoo.klgcourseware.ui.fragment.pronounceTrain.PronounceSlowRepeatTrainFragment;
import com.lancoo.klgcourseware.utils.klog.KLog;
import com.stkouyu.entity.LgEvaluateObj;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


/**
 * Created by pengmi on 2019/8/15 18:34
 * Description:发音训练
 */
public class PronunciatioTrainFragment extends BasicTrainBaseFragment implements KlgMediaManager.OnPlayListener{

    private static final String TAG = "PronunciatioTrainFragme";
    public static final String PRONOUNCE_READING="reading";
    public static final String PRONOUNCE_REPEAT_SLOW="repeat_slow";
    public static final String PRONOUNCE_REPEAT_FAST="repeat_fast";
    private WordArticulation wordArticulation;
    private String currentTag=PRONOUNCE_REPEAT_SLOW;
    private PronounceBaseFragment currentFragment;
    private PronounceBaseFragment.PronounceState currentPronounceState;
    private KlgMediaManager repeatMediaManager;
    private KlgLocalMediaManager resultMediaManager;
    private int slowScore,fastScore;
    private String slowRecordUrl,fastRecordUrl;


    @Override
    protected int getContentViewId() {
        return R.layout.klg_fragment_pronunciatio_train;
    }

    @Override
    protected void initView(View view) {
        wordArticulation = (WordArticulation) getArguments().getSerializable(KEY_SPELL_ARTICULATION);
        currentTrainTag=TRAINTAG_PHONETIC;
        if(wordArticulation==null){
            showEmptyLayout();
        }else{
            initData(view);
            currentPronounceState= PronounceBaseFragment.PronounceState.SLOWDREAD;
            startPronunciatioTrainMode(PRONOUNCE_READING);
            enableStartTrain(0);
        }
    }

    private void initData(View view){
        ViewStub viewStub = view.findViewById(R.id.viewstub_main_data);
        if(viewStub!=null){
            viewStub.inflate();
            resultMediaManager=new KlgLocalMediaManager();
            repeatMediaManager = new KlgMediaManager(getContext());
            KlgCommonBean commonBean = (KlgCommonBean) getArguments().getSerializable(KlgBasicTrainActivity.KEY_KLGCOMMONBEN);
            repeatMediaManager.setUpMedia(commonBean.getUs_voice(),this);
        }
    }


    private void startPronunciatioTrainMode(String tag){
        if(TextUtils.equals(tag,currentTag)||getContext()==null){
            return;
        }
        FragmentTransaction fragmentTransaction = getChildFragmentManager().beginTransaction();
        if(currentFragment!=null){
            fragmentTransaction.hide(currentFragment);
        }
        PronounceBaseFragment pronounceBaseFragment = (PronounceBaseFragment) getChildFragmentManager().findFragmentByTag(tag);

        if(pronounceBaseFragment==null){
            switch (tag){
                case PRONOUNCE_READING:
                    pronounceBaseFragment=new PronounceReadingTrainFragment();
                    break;
                case PRONOUNCE_REPEAT_SLOW:
                    pronounceBaseFragment=new PronounceSlowRepeatTrainFragment();
                    break;
                case PRONOUNCE_REPEAT_FAST:
                    pronounceBaseFragment=new PronounceFastRepeatTrainFragment();
                    break;
            }
            Bundle bundle=new Bundle();
            bundle.putSerializable(KEY_SPELL_ARTICULATION,wordArticulation);
            bundle.putBoolean(KEY_ISMORE_ENTER,getArguments().getBoolean(KEY_ISMORE_ENTER));
            bundle.putBoolean(KEY_IS_ALERT,getArguments().getBoolean(KEY_IS_ALERT));
            if(pronounceBaseFragment!=null){
                pronounceBaseFragment.setArguments(bundle);
            }
            fragmentTransaction.add(R.id.framelayout,pronounceBaseFragment,tag);
        }else{
            fragmentTransaction.show(pronounceBaseFragment);
        }
        fragmentTransaction.commitAllowingStateLoss();
        currentFragment=pronounceBaseFragment;
        currentTag=tag;

    }


    /**
     *开始训练 从3，2，1倒计时开始
     */
    protected void startTrain(){
        Log.e(TAG,"onTrainStart");
//        startTrainDialogCountTime();
        if(currentFragment==null){
            return;
        }
        if(currentFragment.enableResetProgress()){
            recorderProgress=0;
        }else{
            recorderProgress=currentFragment.getFastReadingStartProgress();
        }
        upDateRecordProgress();
        if(TextUtils.equals(currentTag,PRONOUNCE_READING)){
            Log.e("aaaaa","嘟一声后，朗读开始训练");
            startCountTimeTimer();
            startSpeechEvaluation(wordArticulation.getKlgName(),"");
            currentFragment.startTrain();
        }else{
            Log.e("aaaaa","嘟一声后，跟读开始训练");
            repeatMediaManager.changePlaySpeed(currentPronounceState==PronounceBaseFragment.PronounceState.SLOWREPEAT?0.8f:1.2f);
            repeatMediaManager.seekTo(0);
            repeatMediaManager.start();
            currentFragment.startTrain();
            secondCountTime=REPEAT_TIME;
            trainCountTime=MEDIAREPEAT_TIME;
            startSecondTimer();
        }
//        upDateRecordProgress();
//        startCountTimeTimer();
//        startSpeechEvaluation(wordArticulation.getKlgName(),"");
//        currentFragment.onTrainStart();
    }


    /**
     * 更新录音作答时长进度
     */
    protected void upDateRecordProgress(){
        if(currentFragment==null){
            return;
        }
        currentFragment.upDateRecordProgress(recorderProgress);
//        if(donutProgress!=null){
//            donutProgress.setProgress(recorderProgress);
//            if(recorderProgress>(mAdapter.getShowIndex()+1)*splitTime){
//                mAdapter.changeRepeat(recorderProgress/splitTime);
//                scrollIndex(mRecyclerView,recorderProgress/splitTime,commonBean.getKlgName().length(),true);
//            }
//        }
//        if(recorderProgress>=totalTime){
//            Log.e("aaaa","作答结束");
//            destroyCountTimeTimer();
//            stopSpeechEvaluation();
//        }

    }

    protected void onSuccessSpeechEvaluation(int grade, String url, LgEvaluateObj skegnResult){
        if(currentFragment!=null){
            currentFragment.speechEvaluationSuccess(grade,url,skegnResult);
        }
    }

    /**
     * 中止当前的训练
     */
    protected void pauseCurrentSubTrain(boolean isReset){
        if(currentFragment!=null){
            currentFragment.pauseCurrentPronounceSubTrain(isReset);
        }
        if(repeatMediaManager!=null){
            repeatMediaManager.pause();
        }
        pauseMeidaPlayer();
        if(isReset){
            startPronunciatioTrainMode(PRONOUNCE_READING);
            currentPronounceState=PronounceBaseFragment.PronounceState.SLOWDREAD;
        }

    }


    protected void changePronounceSubTrainModel(PronounceBaseFragment.PronounceState pronounceState){
        Log.e(TAG,"changePronounceSubTrainModel"+pronounceState);
        switch (pronounceState){
            case SLOWDREAD:
                if(currentPronounceState==pronounceState){
                    if(currentFragment!=null){
                        currentFragment.pauseCurrentPronounceSubTrain(true);
                    }
                    enableStartTrain(R.string.klg_start_phonetic_train_alert);
                }else{
                    startPronunciatioTrainMode(PRONOUNCE_REPEAT_SLOW);
                    currentPronounceState=PronounceBaseFragment.PronounceState.SLOWREPEAT;
                    enableStartTrain(R.string.klg_start_repeat_train_alert);
                }
                break;
            case FASTREAD:
                if(currentPronounceState==pronounceState){
                    enableStartTrain(R.string.klg_start_phonetic_train_alert);
                }
                break;
            case SLOWREPEAT:
                if(currentPronounceState!=pronounceState){
                    startPronunciatioTrainMode(PRONOUNCE_REPEAT_SLOW);
                    currentPronounceState=pronounceState;
                    enableStartTrain(R.string.klg_start_repeat_train_alert);
                }
                break;
            case FASTREPEAT:
                startPronunciatioTrainMode(PRONOUNCE_REPEAT_SLOW);
                currentPronounceState=pronounceState;
                enableStartTrain(R.string.klg_start_repeat_train_alert);
                break;
        }
    }


    /**
     * 跟读训练跟读阶段3，2，1倒计时
     */
    protected void upDateSecondCountTime(){
        if(secondCountTime==0){
            pauseSecondTimer();
        }
        if(currentFragment!=null){
            currentFragment.upDateRepeatCountTime(secondCountTime);
        }
    }

    /**
     * 作答评阅结束2s倒计时
     * @param progress
     * @param totalProgress
     */
    protected void upDateResultCountTime(int progress,int totalProgress){
        Log.e("aaaaa",TAG+"作答评阅结束2s倒计时"+progress+"..."+totalProgress);
        if(progress==totalProgress) {
            pauseSecondTimer();
        }
        if(currentFragment!=null){
            currentFragment.upDateResultCountTime(progress,totalProgress);
        }
    }

    /**
     * 发音跟读训练进入下个流程
     * @param score
     * @param recordUrl
     */
    protected void changePronounceRepeatTrainModel(int score,String recordUrl){
        if(TextUtils.equals(currentTag,PRONOUNCE_READING)){
            if(score<50){
                startPronunciatioTrainMode(PRONOUNCE_REPEAT_SLOW);
                currentPronounceState=PronounceBaseFragment.PronounceState.SLOWREPEAT;
                enableStartTrain(0);
            }else{
                enterNextTrainModel();
            }
        }else if(TextUtils.equals(currentTag,PRONOUNCE_REPEAT_SLOW)){
            slowScore=score;
            slowRecordUrl=recordUrl;
            startPronunciatioTrainMode(PRONOUNCE_REPEAT_FAST);
            currentPronounceState=PronounceBaseFragment.PronounceState.FASTREPEAT;
            startDripMusic();
        }else{
            Log.e("TAG","完成快速跟读训练，走结果展示流程");
            fastScore=score;
            fastRecordUrl=recordUrl;
            int grade= (int) (0.2f*slowScore+0.8f*fastScore);
            List<String> urlList=new ArrayList<>();
            urlList.add(slowRecordUrl);
            urlList.add(fastRecordUrl);

            if(grade>=60){
                enterPronounceResultActivity(grade,urlList,getString(R.string.klg_result_repeat));
            }else{
                changePronounceSubTrainModel(PronounceBaseFragment.PronounceState.SLOWREPEAT);
            }
        }
    }

    /**
     * 恢复，继续训练
     */
    protected void continueTrain(){
        switch (currentPronounceState){
            case SLOWDREAD:
            case FASTREAD:
                break;
            case SLOWREPEAT:
                recorderProgress=0;
                break;
            case FASTREPEAT:
                recorderProgress=0;
                break;
        }
        if(currentFragment!=null){
            currentFragment.resumePronounceTrainStudy();
        }

    }

    protected void resetPronounceTrain(){
        if(currentPronounceState==PronounceBaseFragment.PronounceState.SLOWDREAD||
                currentPronounceState==PronounceBaseFragment.PronounceState.FASTREAD){
            if(currentFragment!=null){
                currentFragment.pauseCurrentPronounceSubTrain(true);
            }
            enableStartTrain(R.string.klg_start_phonetic_train_alert);
        }else{
            currentFragment.pauseCurrentPronounceSubTrain(true);
            currentPronounceState=PronounceBaseFragment.PronounceState.SLOWDREAD;
            startPronunciatioTrainMode(PRONOUNCE_READING);
            enableStartTrain(R.string.klg_start_repeat_train_alert);
        }
    }


    @Override
    public void onComplete() {

    }

    @Override
    public void onStartError() {

    }

    @Override
    public void onPausePlay() {

    }

    @Override
    public void onSourceError() {

    }

    @Override
    public void onResumePlay() {

    }

    @Override
    public void onStopPlay() {

    }

    @Override
    public void onPrepare() {

    }

    @Override
    public void onBufferingUpdate(MediaPlayer mp, int percent) {

    }

    @Override
    public void onPause() {
        super.onPause();
        if(repeatMediaManager!=null){
            repeatMediaManager.pause();
        }
        pauseMeidaPlayer();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(repeatMediaManager!=null){
            repeatMediaManager.release();
        }
        if(resultMediaManager!=null){
            resultMediaManager.release();
        }
    }

    protected void updateCountTime(int progress,int totalProgress){
        Log.e("aaaa","发音训练321:"+progress);
        if(currentFragment!=null){
            currentFragment.updateCountTimeProgress(progress,totalProgress);
        }
    }

    protected float getSlowScore(){
        return slowScore;
    }


    private void pauseMeidaPlayer(){
        if(resultMediaManager!=null){
            resultMediaManager.pause();
        }
    }

    protected void quesResultMuiscPlayer(boolean isCorrect){
        if(resultMediaManager==null){
            return;
        }
        try {
            AssetFileDescriptor assetFileDescriptor = getContext().getAssets().openFd(isCorrect?"klg_record_correct.mp3":"klg_record_error.mp3");
            resultMediaManager.setUpMedia(assetFileDescriptor, new KlgLocalMediaManager.OnPlayListener() {
                @Override
                public void onComplete() {

                }

                @Override
                public void onStartError() {

                }

                @Override
                public void onPausePlay() {

                }

                @Override
                public void onSourceError() {

                }

                @Override
                public void onResumePlay() {

                }

                @Override
                public void onStopPlay() {

                }

                @Override
                public void onPrepare() {
                    if(resultMediaManager!=null){
                        resultMediaManager.start();
                    }
                }

                @Override
                public void onBufferingUpdate(MediaPlayer mp, int percent) {

                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
